<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Paginator
 *
 * @author dungnt
 */
class MyPaginator
{

//put your code here
    public $recordcount;
    public $pagesize;
    public $url;
    public $equals;
    public $source;
    public $page;
    public $skip;
    public $counterstart;
    public $counterend;
    public $maxpage;
    public $display;
    public $startrow;

    public function __construct($recordcount, $pagenum, $pagesize = 15)
    {
        $pagenum = is_int((int)$pagenum) ? $pagenum : 0;
        $this->recordcount = $recordcount;
        $this->pagesize = $pagesize;
        $this->skip = ($pagenum - 1) * $pagesize;
        if (empty($pagenum)) {
            if ($$this->startrow == 0) {
                $this->page = $this->startrow + 1;
            }
        } else {
            $this->page = $pagenum;
            $this->startrow = ($this->page - 1) * $this->pagesize;
        }
        $this->counterstart = $this->page;
        $this->maxpage = $recordcount / $this->pagesize;
        if ($recordcount % $this->pagesize == 0) {
            $this->maxpage = $recordcount / $this->pagesize;
        } else {
            $this->maxpage = ceil($recordcount / $this->pagesize);
        }
        if ($this->page <= 3) {
            $this->counterstart = 1;
            $this->counterend = 5;
        } else if ($this->maxpage - $this->page <= 3) {
            $this->counterstart = $this->page - 2 - (2 - ($this->maxpage - $this->page));
            $this->counterend = $this->counterstart + 5;
            if ($this->counterstart == 0) {
                $this->counterstart = 1;
                $this->counterend = $this->maxpage;
            }
        } else {
            $this->counterend = $this->counterstart + 2;
            $this->counterstart = $this->page - 2;
        }
        $this->url = $this->getUrl();
    }

    protected function getUrl()
    {
        $url = $_SERVER['REQUEST_URI'];
        if (preg_match('/\?page=/', $url) || preg_match('/\&page=/', $url)) {
            $pos = strrpos($url, 'page=');
            $url = substr($url, 0, $pos + 2);
        } else {
            if (preg_match('/\?/', $url))
                $url .= '&page=';
            else {
                $url .= '?page=';
            }
        }
        return $url;
    }

}

?>
